package io.renren.modules.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import io.renren.modules.PCguanli.entity.QuestionEntity;
import io.renren.modules.app.dao.RpExamDao;
import io.renren.modules.app.entity.ResidentEntity;
import io.renren.modules.app.entity.RpExamEntity;
import io.renren.modules.app.entity.UserExamEntity;
import io.renren.modules.app.mapper.ExamineMapper;
import io.renren.modules.app.mapper.QuestionMapper;
import io.renren.modules.app.mapper.RpExamMapper;
import io.renren.modules.app.mapper.RpQuestionMapper;
import io.renren.modules.app.service.ResidentService;
import io.renren.modules.app.service.RpExamService;

import io.renren.modules.app.user.Exam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

/**
 * ClassName: UserExamServiceImpl
 * Package: io.renren.modules.app.service.impl
 * Description:
 *
 * @Author zzy
 * @Create 2024/4/17 21:33
 * @Version 1.0
 */

@Service("RpExamService")
public class RpExamServiceImpl extends ServiceImpl<RpExamDao, RpExamEntity> implements RpExamService {

    @Autowired
    private RpExamMapper rpExamMapper;
    @Autowired
    private RpQuestionMapper rpQuestionMapper;
    @Autowired
    private ResidentService residentService;
    @Override
    public boolean upsertRp(RpExamEntity rpExamEntity) {
        if (rpExamEntity.getPicture().length() != 20) {
            return false;
        }
        rpExamEntity.setPicture(rpExamEntity.getPicture().toUpperCase());
        ResidentEntity residentEntity = residentService.getUserById(rpExamEntity.getUserId());
        residentEntity.setDatetime1(rpExamEntity.getValue());
        residentService.updateById(residentEntity);

        return this.save(rpExamEntity);
    }

    @Override
    public List<RpExamEntity> getRecordsByUserId(int userId) {
        QueryWrapper<RpExamEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", userId);
        return this.list(queryWrapper);
    }


    @Override
    public Exam getRpRandomExamQuestions() {
        Integer examNumber = rpExamMapper.getRpRandomExamNumber();
        List<Long> questionNumbers = rpExamMapper.getRpQuestionNumbersForExam(examNumber);
        List<QuestionEntity> questions = rpQuestionMapper.getRpQuestionsByNumbers(questionNumbers);
        return new Exam(examNumber, questions);
    }


    @Override
    public void downloadFile(Integer num, HttpServletResponse response) throws DocumentException, IOException {
        RpExamEntity rpExamEntity = baseMapper.selectById(num);
        Integer examNum = rpExamEntity.getExamNum();
        List<Long> questionNumbers = rpExamMapper.getRpQuestionNumbersForExam(examNum);
        List<QuestionEntity> questions = rpQuestionMapper.getRpQuestionsByNumbers(questionNumbers);
        String picture = rpExamEntity.getPicture();

        // 创建 PDF document
        Document document = new Document();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter pdfWriter = PdfWriter.getInstance(document, baos);

        // 获取系统字体，如果是中文，则需注意linux中不存在windows字体，中文乱码或者写不进去
        FontFactory.registerDirectories();
        Font chineseFont = FontFactory.getFont("SimSun", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        document.open();

        // 发送人字体
        Font titleFont = new Font(chineseFont.getBaseFont(), 14, Font.BOLD, BaseColor.BLACK);
        // 内容字体
        Font textFont = new Font(chineseFont.getBaseFont(), 12);
        Font redFont = new Font(chineseFont.getBaseFont(), 12, Font.BOLD, BaseColor.RED);
        Font greenFont = new Font(chineseFont.getBaseFont(), 12, Font.BOLD, BaseColor.GREEN);

        // Add header to each page
        pdfWriter.setPageEvent(new PdfPageEventHelper() {
            @Override
            public void onEndPage(PdfWriter writer, Document document) {
                Paragraph header = new Paragraph();
                header.add(new Chunk("考试时间: " + rpExamEntity.getTime(), titleFont));
                header.add(new Chunk("   用时: " + rpExamEntity.getUseTime(), titleFont));
                header.add(new Chunk("   分数: " + rpExamEntity.getScore(), titleFont));
                header.add(new Chunk("  考试人: ", titleFont));
                header.setIndentationLeft(20f);
                header.setIndentationRight(20f);
                header.setSpacingAfter(20f);
                ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase(header), 280, 810, 0);
            }
        });

        for (int i = 0; i < questions.size(); i++) {

            QuestionEntity quest = questions.get(i);
            Paragraph paragraph1 = new Paragraph();

            ColumnText columnText1 = new ColumnText(pdfWriter.getDirectContent());
            columnText1.addElement(paragraph1);
            columnText1.setSimpleColumn(20, document.bottom(), document.right() - 20, document.top(), 0, Element.ALIGN_LEFT);

            paragraph1.add(new Chunk((i+1) + "、" + quest.getContent() + "\n", textFont));
            if (StringUtils.isNotEmpty(quest.getA())) {
                paragraph1.add(new Chunk("A. " + quest.getA() + "\n", textFont));
            }
            if (StringUtils.isNotEmpty(quest.getB())) {
                paragraph1.add(new Chunk("B. " + quest.getB() + "\n", textFont));
            }
            if (StringUtils.isNotEmpty(quest.getC())) {
                paragraph1.add(new Chunk("C. " + quest.getC() + "\n", textFont));
            }
            if (StringUtils.isNotEmpty(quest.getD())) {
                paragraph1.add(new Chunk("D. " + quest.getD() + "\n", textFont));
            }
            paragraph1.add(new Chunk("正确答案 " + quest.getCorrectanswer(), textFont));
            if (quest.getCorrectanswer().equals("" + picture.charAt(i))) {
                paragraph1.add(new Chunk("    你的答案 " + picture.charAt(i) + "\n", greenFont));
            } else {
                paragraph1.add(new Chunk("    你的答案 " + picture.charAt(i) + "\n", redFont));
            }

            paragraph1.setIndentationLeft(20f);
            paragraph1.setIndentationRight(20f);
            paragraph1.setSpacingAfter(10f);

            // 判断当前页内容是否已满
            if (ColumnText.hasMoreText(columnText1.go())) {
                document.newPage();
            }
            document.add(paragraph1);

        }
        document.close();
// 创建一个 PdfReader 对象
        PdfReader reader = new PdfReader(baos.toByteArray());
        // 创建一个新的 ByteArrayOutputStream 对象
        ByteArrayOutputStream baosWithWatermark = new ByteArrayOutputStream();
        // 创建一个 PdfStamper 对象
        PdfStamper stamper = new PdfStamper(reader, baosWithWatermark);

        Image watermark = Image.getInstance(rpExamEntity.getNamePicture());
        watermark.setAbsolutePosition(520, 780);
        watermark.scaleAbsolute(50, 50);
        watermark.setRotationDegrees(90);
        PdfGState gs = new PdfGState();
        gs.setFillOpacity(1.0f); // 设置填充透明度，1.0f 表示完全不透明，0.0f 表示完全透明
        gs.setStrokeOpacity(1.0f); // 设置描边透明度，1.0f 表示完全不透明，0.0f 表示完全透明

        // 获取 PDF 的页数
        int numberOfPages = reader.getNumberOfPages();

        // 在每一页上添加水印
        for (int i = 1; i <= numberOfPages; i++) {

            PdfContentByte content = stamper.getUnderContent(i);
            content.setGState(gs); // 应用透明度设置
            content.addImage(watermark);
        }

        // 关闭 PdfStamper
        stamper.close();

        //返回pdf
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "inline; filename=exam.pdf");
        response.getOutputStream().write(baosWithWatermark.toByteArray());
        response.getOutputStream().flush();
    }
}

